<?php

namespace App\GraphQL\Queries\Bill;

use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Models\Bill;

class QueryList
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $authUser = auth()->user();
        $data = $args['input'];
        $query = Bill::query();
        $incomeQuery = Bill::query();
        $outlayQuery = Bill::query();
        if($data['year']){
            $startTime = $data['year'].'-01-01 00:00:00';
            $endTime = $data['year'].'-12-31 23:59:59';
            $query->whereBetween('created_at',[$startTime,$endTime]);
            $incomeQuery->whereBetween('created_at',[$startTime,$endTime]);
            $outlayQuery->whereBetween('created_at',[$startTime,$endTime]);
        }
        if(request()->header('mode')==='wechats'){
            $query->where('channel','WECHAT')->where('member_id',$authUser->id);
            $incomeQuery->where('channel','WECHAT')->where('member_id',$authUser->id);
            $outlayQuery->where('channel','WECHAT')->where('member_id',$authUser->id);
        }else if(request()->header('mode')==='alipays'){
            $query->where('channel','ALIPAY')->where('member_id',$authUser->id);
            $incomeQuery->where('channel','ALIPAY')->where('member_id',$authUser->id);
            $outlayQuery->where('channel','ALIPAY')->where('member_id',$authUser->id);
        }
        $result = $query->paginate($data['limit'] ,['*'],'page', $data['page']);
        $income = $incomeQuery->where('type','INPUT')->sum('fee');
        $outlay = $outlayQuery->where('type','OUTPUT')->sum('fee');
        return [
            'data'=>$result->items(),
            'income'=>$income,
            'outlay'=>$outlay,
            'paginatorInfo'=>[
                'count'=>$result->count(),
                'currentPage'=>$result->currentPage(),
                'firstItem'=>$result->firstItem(),
                'hasMorePages'=>$result->hasMorePages(),
                'lastItem'=>$result->lastItem(),
                'lastPage'=>$result->lastPage(),
                'perPage'=>$result->perPage(),
                'total'=>$result->total()
            ]
        ];
    }
}
